package top.pcat.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import top.pcat.entity.ANSI;
import top.pcat.util.MesUtils;
import top.pcat.entity.Message;
import top.pcat.codecs.MessageCodec;

import java.net.InetSocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

@Slf4j
public class Client {

    private String senderName="无名";

    private String senderId;

    public static Map<Long, String> roomMap = new HashMap<>();

    public static long roomId = 0;

    public static String roomName = "服务器";

    private int port;
    private String ip;

    public Client() {
    }
    public Client(String senderId,String senderName,String ip,int port) {
        this.senderId = senderId;
        this.senderName = senderName;
        this.port = port;
        this.ip = ip;
    }


    public void client() throws Exception {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast("encoder",new StringEncoder());
//                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1024000, 0, 4, 0, 0));
                            //pipeline.addLast(new LengthFieldPrepender(4));
                            pipeline.addLast(new MessageCodec());
                            pipeline.addLast(new ClientHandler(senderId,senderName,roomMap,roomName,roomId));
                        }
                    });
            log.info("来自客户端的消息 ----->  客户端准备就绪");
            System.out.println("║            > 网关连接成功！正在为你连接"+ANSI.ANSI_YELLOW+ip+":"+port+ANSI.ANSI_GREEN+"服务器！     ");
            //连接服务端
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();

            channelFuture.addListener(future -> {
                if(future.isSuccess()){
                    log.info("来自客户端的消息 ----->  客户端启动中..."+port);
                }
                if(future.isDone()){
                    log.info("来自客户端的消息 ----->  客户端启动成功...OK！");
                    System.out.println("║            > 连接成功，聊天室已就绪！                 ");
                    System.out.println("╠══════════════════════════════════════════════════════════════════");
                    System.out.println("╟"+ANSI.ANSI_BLUE+"            @ <消息内容> : 发送随机私聊消息。              ");
                    System.out.println(ANSI.ANSI_GREEN+"╟"+ANSI.ANSI_BLUE+"            # <数量>-<总金额> : 发送红包，每个红包随机分配。 ");
                    System.out.println(ANSI.ANSI_GREEN+"╟"+ANSI.ANSI_BLUE+"            % <红包ID> : 领取对应的红包。                  ");
                    System.out.println(ANSI.ANSI_GREEN+"╟"+ANSI.ANSI_BLUE+"            & : 退出当前聊天室。                  ");
                    System.out.println(ANSI.ANSI_GREEN+"╠══════════════════════════════════════════════════════════════════");
                }
            });



            InetSocketAddress socketAddress = (InetSocketAddress) channelFuture.channel().localAddress();
            int hashCode = socketAddress.hashCode();


            Channel channel = channelFuture.channel();

            //第一条消息介绍自己
            Message firstMessage = new Message("0",senderName,"介绍信");

            //log.info(senderId);
            firstMessage.setSenderId(senderId);
            firstMessage.setDate(new Date());
            log.info("我的ip地址  --------->  " + socketAddress.toString() +" senderId:" + senderId);
            channel.writeAndFlush(firstMessage);


            //聊天室部分
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNextLine()){
                String str = scanner.nextLine();

                if (str.charAt(0)=='&'){
                    log.info("用户新建聊天室");

                    String roomName = str.substring(2);
                    log.info("用户要新建的roomName为"+roomName);

                    Message message1 = new Message(senderId,senderName,0,roomName,"newRoom",roomName,6,new Date());
                    channel.writeAndFlush(message1);

                }else{
                    log.info("用户选择已有的聊天室");

                    try{
                        roomId = Long.parseLong(str);

                        Message message1 = new Message(senderId,senderName,Long.parseLong(str),"","choosed",str,2,new Date());
                        channel.writeAndFlush(message1);
                        log.info("确认聊天室的消息 ----->  "+message1);
                        roomName = roomMap.get(roomId);
                        break;
                    }catch (NumberFormatException numberFormatException){
                        continue;
                    }
                }

            }


//            Scanner scanner = new Scanner(System.in);
//            //log.info("输入序号");
//            String str = scanner.next();//senderId, str, 1, senderName
//            //log.info("输入了"+str);
//
//            Message message1 = new Message(senderId,senderName,Long.parseLong(str),"","choosed",str,2,new Date());




            //log.info("cc"+roomMap);
            //roomName = roomMap.get(roomId);
           // log.info(roomId+"设置rooName"+roomName);

            //聊天
           // senMes(senderId,channel,roomId);

            //scanner.nextLine();
            //log.info("123");
            while(scanner.hasNextLine()){
                String strr = scanner.nextLine();
                //Message message = new Message(132,"pc",str);

                if (strr == null || strr.equals("") || strr.equals("\n")){
                    continue;
                }

                char c = strr.charAt(0);


                if (c=='#') {
                    log.info("输入红包数量（个）和红包金额（元），格式：10-1");
                    String s = strr.substring(2);
                    //log.info("收到数值" + s);

                    Message messagehb = new Message();
                    messagehb.setRoomId(roomId);
                    messagehb.setController(3);
                    messagehb.setRoomName(roomName);
                    messagehb.setMesContent(s);
                    messagehb.setDate(new Date());
                    messagehb.setSenderId(senderId);
                    messagehb.setSenderName(senderName);
                    messagehb.setMesType("hongbao");

                    messagehb.setDate(new Date());
                    channel.writeAndFlush(messagehb);
                    log.info("发送红包消息 ----->  " + messagehb);

                }else if(c == '%') {
                    //log.info("抢红包");
                    String hbtime = strr.substring(1);

                    Message messagehb = new Message();
                    messagehb.setRoomId(roomId);
                    messagehb.setRoomName(roomName);
                    messagehb.setController(4);
                    messagehb.setMesContent(hbtime);
                    messagehb.setDate(new Date());
                    messagehb.setSenderId(senderId);
                    messagehb.setSenderName(senderName);
                    messagehb.setMesType("qianghongbao");
                    messagehb.setDate(new Date());
                    channel.writeAndFlush(messagehb);
                    //log.info("发送抢红包消息 ----->  " + messagehb);

                }else if(c == '@') {
                    log.info("随机私聊");
                    String msgg = strr.substring(2);

                    Message messagehb = new Message();
                    messagehb.setRoomId(roomId);
                    messagehb.setRoomName(roomName);
                    messagehb.setController(5);
                    messagehb.setMesContent(msgg);
                    messagehb.setDate(new Date());
                    messagehb.setSenderId(senderId);
                    messagehb.setSenderName(senderName);
                    messagehb.setMesType("随机私聊");
                    messagehb.setDate(new Date());
                    channel.writeAndFlush(messagehb);
                    log.info("发送随机私聊消息 ----->  " + messagehb);

                }else if (c == '^'){
                    log.info("循环消息");

                    for (int i=0; i < 100;i++){
                        Message message1r = MesUtils.SendUserMsg(senderId, String.valueOf(i), roomId, senderName);
                        message1r.setDate(new Date());
                        channel.writeAndFlush(message1r);
                        log.info("发送普通消息消息 ----->  " + i);
                    }
                }else if (c=='*'){
                    String s = null;
                    for (long i=0; i < 1000;i++){
                        s = s+ ":" + String.valueOf(i);
                    }
                    log.info("发送普通消息消息 ----->  " + s);
                    Message message1r = MesUtils.SendUserMsg(senderId, s, roomId, senderName);
                    message1r.setDate(new Date());
                    channel.writeAndFlush(message1r);
                    log.info("发送普通消息消息 ----->  " + s);
                }else if( c == '&'){
                    log.info("退出当前聊天室");
                }else {
                    log.info("普通消息");

                    Message message1r = MesUtils.SendUserMsg(senderId, strr, roomId, senderName);
                    message1r.setDate(new Date());
                    channel.writeAndFlush(message1r);
                    log.info("发送普通消息消息 ----->  " + message1r);

                }

            }
            scanner.close();


            channelFuture.channel().closeFuture().sync();

        } finally {
            //关闭线程组
            eventExecutors.shutdownGracefully();
        }
    }

//    public void senMes(String senderId,Channel channel,long roomId){
//        //Scanner scanner = new Scanner(System.in);
//        log.info("123");
//        while(scanner.hasNextLine()){
//            String str = scanner.nextLine();
//            //Message message = new Message(132,"pc",str);
//            Message message1 = MesUtils.SendUserMsg(senderId, str, roomId, senderName);
//            message1.setDate(new Date());
//            channel.writeAndFlush(message1);
//            log.info("自己发送的消息 ----->  "+message1);
//        }
//        scanner.close();
//    }
}
